<template>
  <div id='LabMainInfoLog'>
    <div class='areaAll'>
      <Splitpanes horizontal>
        <Pane size="50">
          <div class='tableBody'>
            <vxe-table ref='logTable' border height='auto' class='mytable-scrollbar'
                       :data='logList'
                       :loading='loading'
                       :expand-config='{ expandAll: true, reserve: true }'
                       :row-config='{ isCurrent: true, isHover: true }'
                       :keyboard-config='{isArrow: true,isTab: true,isEdit: true}'
                       :edit-config="{ trigger: 'dblclick', mode: 'row', showStatus: true }"
                       resizable show-overflow keep-source @current-change='roleRowClick'>
              <vxe-column field='userName' width='100' title='操作人'></vxe-column>
              <vxe-column field='operateTime' width='200' title='操作时间' :formatter='formatTime'></vxe-column>
              <vxe-column field='updateField' title='修改字段'></vxe-column>
              <vxe-column field='originalResult' title='原始结果'></vxe-column>
              <vxe-column field='amendedResult' title='修改结果'></vxe-column>
              <vxe-column field='sampleDate' title='检验日期' :formatter='formatDate'></vxe-column>
              <vxe-column field='sampleNumber' title='样本号'></vxe-column>
            </vxe-table>

            <vxe-pager
                align='left'
                max-height='32px'
                :current-page.sync='page.currentPage'
                :page-size.sync='page.pageSize'
                :total='page.totalResult'
                :layouts="['PrevJump','PrevPage','Number','NextPage','NextJump','Sizes','FullJump','Total']"
                @page-change='handleSizeChange($event)'
            ></vxe-pager>
          </div>
        </Pane>
        <Pane size="50">
          <div class='tableBody1'>
            <vxe-table ref='logTable' border height='auto' class='mytable-scrollbar'
                       :data='resultLogList'
                       :loading='resultLoading'
                       :expand-config='{ expandAll: true, reserve: true }'
                       :row-config='{ isCurrent: true, isHover: true }'
                       :keyboard-config='{isArrow: true,isTab: true,isEdit: true}'
                       :edit-config="{ trigger: 'dblclick', mode: 'row', showStatus: true }"
                       resizable show-overflow keep-source>
              <vxe-column field='itemNa' title='项目名称'></vxe-column>
              <vxe-column field='itemNo' title='项目编号'></vxe-column>
              <vxe-column field='originalResult' title='原始结果'></vxe-column>
              <vxe-column field='amendedResult' title='修改结果'></vxe-column>
              <vxe-column field='amendedUserName' title='操作人员'></vxe-column>
              <vxe-column field='amendedDate' width='200' title='操作时间' :formatter='formatTime'></vxe-column>
            </vxe-table>

            <vxe-pager
                align='left'
                max-height='32px'
                :current-page.sync='Resultpage.currentPage'
                :page-size.sync='Resultpage.pageSize'
                :total='Resultpage.totalResult'
                :layouts="['PrevJump','PrevPage','Number','NextPage','NextJump','Sizes','FullJump','Total']"
                @page-change='handleResultSizeChange($event)'
            ></vxe-pager>
          </div>
        </Pane>
      </Splitpanes>


      <el-dialog title='操作日志详情' width='1200px' append-to-body v-model='showLogDetails' style='margin-top: 10vh'>
        <el-descriptions :column='2' border v-loading='dialogLoading'>
          <el-descriptions-item>
            <template #label>
              <div class='cell-item'>
                <el-icon :style='iconStyle'>
                  <user />
                </el-icon>
                操作人员
              </div>
            </template>
            {{ formDetails.userName }}
          </el-descriptions-item>
          <el-descriptions-item>
            <template #label>
              <div class='cell-item'>
                <el-icon :style='iconStyle'>
                  <AlarmClock />
                </el-icon>
                操作时间
              </div>
            </template>
            {{ formDetails.operateTime }}
          </el-descriptions-item>
          <el-descriptions-item>
            <template #label>
              <div class='cell-item'>
                <el-icon :style='iconStyle'>
                  <iphone />
                </el-icon>
                操作模块
              </div>
            </template>
            {{ formDetails.module }}
          </el-descriptions-item>
          <el-descriptions-item>
            <template #label>
              <div class='cell-item'>
                <el-icon :style='iconStyle'>
                  <ChatSquare />
                </el-icon>
                操作內容
              </div>
            </template>
            {{ formDetails.content }}
          </el-descriptions-item>
          <el-descriptions-item>
            <template #label>
              <div class='cell-item'>
                <el-icon :style='iconStyle'>
                  <Monitor />
                </el-icon>
                计算机
              </div>
            </template>
            <el-tag size='small'>{{ formDetails.machineName }}</el-tag>
          </el-descriptions-item>
          <el-descriptions-item>
            <template #label>
              <div class='cell-item'>
                <el-icon :style='iconStyle'>
                  <office-building />
                </el-icon>
                IP地址
              </div>
            </template>
            <el-tag size='small'>{{ formDetails.machineIp }}</el-tag>
          </el-descriptions-item>
          <el-descriptions-item>
            <template #label>
              <div class='cell-item'>
                <el-icon :style='iconStyle'>
                  <tickets />
                </el-icon>
                请求方式
              </div>
            </template>
            <el-tag size='small'>{{ formDetails.requestMethod }}</el-tag>
          </el-descriptions-item>
          <el-descriptions-item>
            <template #label>
              <div class='cell-item'>
                <el-icon :style='iconStyle'>
                  <Location />
                </el-icon>
                请求地址
              </div>
            </template>
            <el-tag size='small'>{{ formDetails.requestUrl }}</el-tag>
          </el-descriptions-item>
          <el-descriptions-item>
            <template #label>
              <div class='cell-item'>
                <el-icon :style='iconStyle'>
                  <Timer />
                </el-icon>
                消耗时间
              </div>
            </template>
            <el-tag size='small'>{{ formDetails.takeTime }}/毫秒</el-tag>
          </el-descriptions-item>
          <el-descriptions-item>
            <template #label>
              <div class='cell-item'>
                <el-icon :style='iconStyle'>
                  <Refresh />
                </el-icon>
                操作状态
              </div>
            </template>
            <el-tag size='small'>
              <div v-if="formDetails.flag === '0'">正常</div>
              <div v-else-if="formDetails.flag === '1'">失败</div>
            </el-tag>
          </el-descriptions-item>
        </el-descriptions>

        <el-descriptions :column='1' border v-if='activeNames' v-loading='dialogLoading'>
          <el-descriptions-item>
            <template #label>
              <div class='cell-item'>
                <el-icon :style='iconStyle'>
                  <Tickets />
                </el-icon>
                请求参数
              </div>
            </template>
            <el-scrollbar>
              <div class='selectable'>{{ formDetails.reqParam }}</div>
            </el-scrollbar>
          </el-descriptions-item>
          <el-descriptions-item>
            <template #label>
              <div class='cell-item'>
                <el-icon :style='iconStyle'>
                  <Tickets />
                </el-icon>
                返回参数
              </div>
            </template>
            <el-scrollbar>
              <div class='selectable'>{{ formDetails.repParam }}</div>
            </el-scrollbar>
          </el-descriptions-item>
        </el-descriptions>
      </el-dialog>
    </div>
  </div>
</template>

<script setup lang='ts'>
// 引入组件区 ==========
import { ref, reactive, getCurrentInstance, onMounted, computed, defineProps } from 'vue';
import { pageSizes, formatDateTime } from '@/utils/common';
import { AppStore } from '@/stores/store';
import { Splitpanes, Pane } from 'splitpanes'; //比例拖拉条
import { VxeMessage, VxeNotifyType } from '@/utils/CommonMessage';

let { proxy }: any = getCurrentInstance();


defineExpose({
  initForm
});

// 全局变量定义区 ==========
const props = defineProps({
  requestUrl: { type: String, default: '' }
});

let store = AppStore();
const size = ref('');
let title = ref('');


let logTable = ref(); //日志表格ref
let logList: any = reactive([]); //日志表格数据
let resultLogList: any = reactive([]); //日志表格数据
let loading = ref(false); //表格加载
let resultLoading = ref(false); //表格加载
let dialogLoading = ref(false); //点击当前行的弹框数据加载

const showLogDetails = ref(false); //弹框展开状态
const activeNames = ref(false); //当身份是管理员时可以看到弹框的最下面3个数据 操作方法 请求和返回参数

let form = reactive({
  beginLog: formatDateTime(getThisMonthFirstDay(), 'yyyy-MM-dd'),
  endLog: formatDateTime(getThisMonthNewDay(), 'yyyy-MM-dd 23:59:59'),
  serviceName: '',
  machineIp: '',
  username: '',
  businessName: ''
});

let formDetails = reactive({
  module: '',
  userName: '',
  reqParam: '',
  repParam: '',
  flag: '',
  takeTime: '',
  serviceName: '',
  hospitalName: '',
  hospitalCode: '',
  machineIp: '',
  content: '',
  method: '',
  requestMethod: '',
  requestUrl: '',
  machineName: '',
  operateTime: '',
  logLevel: ''
});

// 当前选中标本
let rptMaininfo: any = reactive({
  id: '',
  sampleDate: '',
  sampleNo: '',
  rptGroup: ''
});

function initForm(repData: any) {
  rptMaininfo.id = repData.id;
  rptMaininfo.sampleDate = repData.sampleda;
  rptMaininfo.sampleNo = repData.sampleNo;
  rptMaininfo.rptGroup = repData.rptGroup;
  findLogPageList();
  findResultLogPageList();
}

// 条数/页
const PageSizeList = [10, 50, 100, 200, 500];
let page = reactive({
  currentPage: 1,
  pageSize: PageSizeList[1],
  totalResult: 0
});
// 条数/页
const ResultPageSizeList = [10, 50, 100, 200, 500];
let Resultpage = reactive({
  currentPage: 1,
  pageSize: ResultPageSizeList[1],
  totalResult: 0
});

const iconStyle = computed(() => {
  const marginMap = {
    large: '8px',
    default: '6px',
    small: '4px'
  };
  return {
    marginRight: marginMap[size.value] || marginMap.default
  };
});

// 方法定义区 =============
//这个月第一天日期
function getThisMonthFirstDay() {
  let today = new Date();
  today.setDate(1);
  today.setHours(0, 0, 0, 0);
  return today;
}

//当前日期
function getThisMonthNewDay() {
  let today = new Date();
  return today;
}

// 格式化日期时间
function formatTime({ cellValue }) {
  if (cellValue) {
    const date = new Date(cellValue);
    return formatDateTime(date, 'yyyy-MM-dd hh:mm:ss');
  }
  return '-';
}

function formatDate({ cellValue }) {
  if (cellValue) {
    const date = new Date(cellValue);
    return formatDateTime(date, 'yyyy-MM-dd');
  }
  return '-';
}


//点击每页数量
function handleSizeChange({ type, currentPage, pageSize }) {
  if (type === 'size') {
    page.currentPage = 1;
  } else {
    page.currentPage = currentPage;
  }
  page.pageSize = pageSize;
  findLogPageList();
}

//检验结果日志点击每页数量
function handleResultSizeChange({ type, currentPage, pageSize }) {
  if (type === 'size') {
    Resultpage.currentPage = 1;
  } else {
    Resultpage.currentPage = currentPage;
  }
  Resultpage.pageSize = pageSize;
  findResultLogPageList();
}

onMounted(() => {
  findLogPageList();
  findResultLogPageList();
});

// 页面获取日志表格数据
function findLogPageList() {
  loading.value = true;
  logList.length = 0;
  const data = {
    pageIndex: page.currentPage,
    pageSize: page.pageSize,
    mainInfoId: rptMaininfo.id,
    sampleNo: rptMaininfo.sampleNo,
    sampleDate: rptMaininfo.sampleDate,
    rptGroup: rptMaininfo.rptGroup,
  };


  proxy.$http.get('/lab/main/info/log/page', { params: data }).then((res: any) => {
    logList.length = 0;
    logList.push(...res.data.records);
    page.totalResult = res.data.total;
    loading.value = false;
  })
    .catch((err: any) => {
      loading.value = false;
      // VxeMessage('搜索日志列表失败', VxeNotifyType.error);
    });
}

// 页面获取日志表格数据
function findResultLogPageList() {
  resultLoading.value = true;
  resultLogList.length = 0;
  const data = {
    pageIndex: Resultpage.currentPage,
    pageSize: Resultpage.pageSize,
    mainInfoId: rptMaininfo.id,
    sampleNo: rptMaininfo.sampleNo,
    sampleDate: rptMaininfo.sampleDate,
    rptGroup: rptMaininfo.rptGroup,
  };


  proxy.$http.get('/lab/main/info/log/getResultLogPag', { params: data }).then((res: any) => {
    resultLogList.length = 0;
    resultLogList.push(...res.data.records);
    Resultpage.totalResult = res.data.total;
    resultLoading.value = false;
  })
    .catch((err: any) => {
      resultLoading.value = false;
      // VxeMessage('搜索日志列表失败', VxeNotifyType.error);
    });
}

// 清空弹框
function clearDialog() {
  // 全部清空
  formDetails.content = '';
  formDetails.userName = '';
  formDetails.reqParam = '';
  formDetails.repParam = '';
  formDetails.flag = '';
  formDetails.serviceName = '';
  formDetails.hospitalName = '';
  formDetails.hospitalCode = '';
  formDetails.machineIp = '';
  formDetails.method = '';
  formDetails.requestMethod = '';
  formDetails.requestUrl = '';
  formDetails.takeTime = '';
  formDetails.module = '';
  formDetails.machineName = '';
  formDetails.operateTime = '';
}

// 获取当前条的详情信息
const roleRowClick = ({ row }: any) => {
  let userInfo = store.userInfo;
  if (userInfo.realname === '管理员') {
    activeNames.value = true;
  }
  showLogDetails.value = true;
  clearDialog(); //清空前面弹框数据
  dialogLoading.value = true;

  formDetails.content = row.content;
  formDetails.userName = row.userName;
  formDetails.reqParam = row.requestParam;
  formDetails.repParam = row.responseParam;
  formDetails.flag = '0';
  formDetails.serviceName = row.serviceName;
  formDetails.hospitalName = row.hospitalName;
  formDetails.hospitalCode = row.hospitalCode;
  formDetails.machineIp = row.machineIp;
  formDetails.method = row.method;
  formDetails.requestMethod = row.requestMethod;
  formDetails.requestUrl = row.requestUrl;
  formDetails.takeTime = row.takeTime;
  formDetails.module = row.module;
  formDetails.machineName = row.machineName;
  formDetails.operateTime = row.operateTime ? formatDateTime(row.operateTime, 'yyyy-MM-dd hh:mm:ss') : '';
  dialogLoading.value = false;
};
</script>
<style lang='scss' scoped>
.selectable {
  -webkit-user-select: text; /* Safari 和 Chrome */
  -moz-user-select: text; /* Firefox */
  -ms-user-select: text; /* Internet Explorer/Edge */
  user-select: text; /* 标准语法 */
  max-width: 700px;
  width: auto;
  min-height: 200px;
  height: auto;
  overflow-wrap: break-word;
}

#LabMainInfoLog {
  height: 100%;

  .areaAll {
    height: 100%;

    .smallTitle {
      margin-right: 5px;
    }

    .searchBtn {
      margin-left: 5px;
    }

    .tableBody {
      height: calc(100% - 30px);
      // 每个单元格左内边距
      :deep(.vxe-cell) {
        padding-left: 5px;
      }
    }
    .tableBody1{
      height: calc(100% - 30px - 35px);
      // 每个单元格左内边距
      :deep(.vxe-cell) {
        padding-left: 5px;
      }
    }

    // 弹框
    .el-dialog {
      font-weight: 700;
      max-height: 1000px;

      .el-descriptions {
        width: 100%;
      }
    }
  }
}

// 操作日志详情弹框的label标签统一宽度
:deep(.el-descriptions__label) {
  width: 150px;
}
</style>
